﻿//Copyright (c) 2009, Offbeat Guides
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other materials 
//provided with the distribution.
//
//* Neither the name of Offbeat Guides nor the names of its contributors may be used to 
//endorse or promote products derived from this software without specific prior written 
//permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
//OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
//TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace Amazon.Services.EC2
{
    internal class EC2QueryService : ServiceClient
    {
        #region Constructors and Finalizers
        public EC2QueryService(AmazonAccount account)
            : base(account, EC2Configuration.Default) { }

        public EC2QueryService(AmazonAccount account, EC2Configuration configuration)
            : base(account, configuration) { }
        #endregion

        #region Methods
        private String GenerateSignature(String method, String key, IDictionary<String, String> parameters)
        {
            KeyedHashAlgorithm algorithm = new HMACSHA1();
            String data = null;
            switch (this.Configuration.SignatureVersion)
            {
                case "0":
                    data = String.Format("{0}{1}", parameters["Action"], parameters["Timestamp"]);
                    break;
                case "1":
                    data = this.CalculateStringToSignV1(parameters);
                    break;
                case "2":
                    if (!parameters.ContainsKey("SignatureMethod"))
                        parameters.Add("SignatureMethod", this.Configuration.SignatureMethod);

                    algorithm = KeyedHashAlgorithm.Create(this.Configuration.SignatureMethod);
                    data = this.CalculateStringToSignV2(method, parameters);
                    break;
                default:
                    throw new Exception("Invalid Signature Version specified");
            }

            algorithm.Key = ServiceClient.Encoding.GetBytes(key);
            Byte[] buffer = ServiceClient.Encoding.GetBytes(data.ToCharArray());
            buffer = algorithm.ComputeHash(buffer);
            return Convert.ToBase64String(buffer);
        }

        private String CalculateStringToSignV1(IDictionary<String, String> parameters)
        {
            IDictionary<String, String> sortedParameters = new SortedDictionary<String, String>(parameters, StringComparer.OrdinalIgnoreCase);

            StringBuilder parameterValues = new StringBuilder();
            foreach (KeyValuePair<String, String> pair in sortedParameters)
            {
                if (pair.Value != null)
                    parameterValues.AppendFormat("{0}{1}", pair.Key, pair.Value);
            }

            return parameterValues.ToString();
        }

        private String CalculateStringToSignV2(String method, IDictionary<String, String> parameters)
        {
            IDictionary<String, String> sortedParameters = new SortedDictionary<String, String>(parameters, StringComparer.Ordinal);

            Uri endpoint = new Uri(this.Configuration.ServiceUrl.ToLower());
            String uri = String.IsNullOrEmpty(endpoint.AbsolutePath) ? "/" : endpoint.AbsolutePath;

            StringBuilder parameterValues = new StringBuilder();
            foreach (KeyValuePair<String, String> pair in sortedParameters)
            {
                if (pair.Value != null)
                    parameterValues.AppendFormat("{0}={1}&", Utility.UrlEncode(pair.Key), Utility.UrlEncode(pair.Value));
            }

            return String.Format("{0}\n{1}\n{2}\n{3}",
                method,
                endpoint.Host,
                Utility.UrlEncode(uri).Replace("%2F", "/"),
                parameterValues.Remove(parameterValues.Length - 1, 1).ToString());
        }
        #endregion

        #region Overriden Methods
        protected override WebRequest CreateRequest(IDictionary<String, String> parameters, Byte[] contents)
        {
            // add required request parameters
            if (!parameters.ContainsKey("AWSAccessKeyId"))
                parameters.Add("AWSAccessKeyId", this.Account.Key);
            if (!parameters.ContainsKey("Timestamp"))
                parameters.Add("Timestamp", DateTime.UtcNow.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z", CultureInfo.InvariantCulture));
            if (!parameters.ContainsKey("Version"))
                parameters.Add("Version", this.Configuration.ServiceVersion);
            if (!parameters.ContainsKey("SignatureVersion"))
                parameters.Add("SignatureVersion", this.Configuration.SignatureVersion);
            if (!parameters.ContainsKey("Signature"))
                parameters.Add("Signature", OAuth.GenerateSignature(this.Configuration, "POST", this.Account.SecretKey, parameters));

            String queryString = Utility.ToQueryString(parameters);
            Byte[] contentData = ServiceClient.Encoding.GetBytes(queryString);

            // create a request to the servers
            HttpWebRequest request = WebRequest.Create(this.Configuration.ServiceUrl) as HttpWebRequest;
            request.UserAgent = this.Configuration.UserAgent;
            request.Method = "POST";
            request.Timeout = 50000;
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            request.ContentLength = contentData.Length;

            // if a proxy host is defined, then use it for requests.
            if (!String.IsNullOrEmpty(this.Configuration.ProxyHost))
                request.Proxy = new WebProxy(this.Configuration.ProxyHost, this.Configuration.ProxyPort);

            // write out the request to the stream
            using (Stream stream = request.GetRequestStream())
                stream.Write(contentData, 0, contentData.Length);

            return request;
        }
        #endregion
    }
}
